package com.hack4jp.hackearthquakes;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import twitter4j.TwitterException;
import twitter4j.auth.OAuthAuthorization;
import twitter4j.conf.ConfigurationBuilder;
import twitter4j.internal.http.HttpParameter;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class TwitpicUpload {
	
	private final static String 
   		TWITPIC_API_URL="http://api.twitpic.com/2/upload.json",
   		AUTH_PROVIDER_URL="https://api.twitter.com/1/account/verify_credentials.json",
		AUTH_REALM_URL="http://api.twitter.com/";
	
	TwitpicUpload(String consumerKey, String consumerSecret, String accessToken, String tokenSecret, String twitpicApiKey)
	{
		_consumerKey = consumerKey;
		_consumerSecret = consumerSecret;
		_accessToken = accessToken;
		_tokenSecret = tokenSecret;
		_twitpicApiKey = twitpicApiKey;
		
  	  ConfigurationBuilder cb = new ConfigurationBuilder();
  	  cb.setMediaProviderAPIKey(_twitpicApiKey);
  	  cb.setOAuthConsumerKey(_consumerKey);
  	  cb.setOAuthConsumerSecret(_consumerSecret);    	  
	  cb.setOAuthAccessToken(_accessToken);  
	  cb.setOAuthAccessTokenSecret(_tokenSecret);    

	  twitter4j.conf.Configuration conf = cb.build();		
		
	  _oauth = new OAuthAuthorization(conf);
	}
	
	private OAuthAuthorization _oauth;
	private String _consumerKey;
	private String _consumerSecret;
	private String _accessToken;
	private String _tokenSecret;
	private String _twitpicApiKey;
	
	protected String generateVerifyCredentialsAuthorizationHeader() {
		List<HttpParameter> oauthSignatureParams = _oauth.generateOAuthSignatureHttpParams("GET", AUTH_PROVIDER_URL);
		return "OAuth realm=\"" + AUTH_REALM_URL + "\"," + OAuthAuthorization.encodeParameters(oauthSignatureParams, ",", true);
	}
	
	public String upload(File imgFile, String message) throws TwitterException, JSONException, ParseException, IOException
	{
		String imgUrl = null;	
				
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(TWITPIC_API_URL);
		
		String verifyCredentials = generateVerifyCredentialsAuthorizationHeader();
		post.addHeader("X-Auth-Service-Provider", AUTH_PROVIDER_URL);
		post.addHeader("X-Verify-Credentials-Authorization", verifyCredentials);
		
		MultipartEntity params = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
		params.addPart("key", new StringBody(_twitpicApiKey, Charset.forName("UTF-8")));
		params.addPart("message", new StringBody(message, Charset.forName("UTF-8")));
		params.addPart("media", new FileBody(imgFile, "image/jpeg" ));
		post.setEntity(params);	
		
		HttpResponse httpResponse = client.execute(post);
		StatusLine status = httpResponse.getStatusLine();
		
		int statusCode = status.getStatusCode();
		if (statusCode != 200)
		{
			throw new TwitterException("upload error " + status);
		}

	    HttpEntity entity = httpResponse.getEntity();
	    String response = EntityUtils.toString(entity);

		JSONObject json = new JSONObject(response);
		if (!json.isNull("url")) {
			imgUrl = json.getString("url");
		}
		
		return imgUrl;
	}
}
